package cn.com.dashihui.web.controller;

import java.util.List;

import org.apache.shiro.authc.credential.DefaultPasswordService;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;

import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Record;

import cn.com.dashihui.kit.ValidateKit;
import cn.com.dashihui.web.base.BaseController;
import cn.com.dashihui.web.dao.Admin;
import cn.com.dashihui.web.service.AdminService;
import cn.com.dashihui.web.service.RoleService;


@RequiresAuthentication
public class AdminController extends BaseController{
//	private static final Logger logger = Logger.getLogger(AdminController.class);
	private AdminService adminService = new AdminService();
	private RoleService roleService = new RoleService();
	
	@RequiresPermissions("auth:admin:index")
    public void index(){
		List<Record> jobList=roleService.findAllRoles();//职位
		setAttr("jobList", jobList);
		setAttr("currUser", getCurrentUser());
        render("index.jsp");
    }

	@RequiresPermissions("auth:admin:index")
	public void page(){
		String tel=getPara("tel");
		String name=getPara("name");
		String jobs=getPara("jobs");
		int pageNum = getParaToInt(0, 1);
		int pageSize = getParaToInt("pageSize", PropKit.getInt("constants.pageSize"));
		renderResult(0,adminService.findByPage(pageNum, pageSize,tel,name,jobs));
	}

	@RequiresPermissions("auth:admin:add")
	public void toAdd(){
		render("add.jsp");
	}
	
	/**
	 * 添加
	 * @return -1：异常，0：成功，1：用户名为空，2：用户名过长，3：用户已经存在，4：密码为空，5：密码过长，6：姓名为空，7：姓名过长，8：手机号码为空，9：手机号码不正确，10：备注过长
	 */
	@RequiresPermissions("auth:admin:add")
	public void doAdd(){
		//账号
		String username = getPara("username");
		//密码
		String password = getPara("password");
		//真实姓名
		String trueName = getPara("trueName");
		//手机号码
		String phonenumber = getPara("phonenumber");
		//备注
		String remark = getPara("remark");
		//是否可用
		int enabled = getParaToInt("enabled",0);
		if(StrKit.isBlank(username)){
			renderResult(1);
			return;
		}else if(username.length()>20){
			renderResult(2);
			return;
		}else if(adminService.findExistsByUsername(username)){
			renderResult(3);
			return;
		}else if(StrKit.isBlank(password)){
			renderResult(4);
			return;
		}else if(password.length()>100){
			renderResult(5);
			return;
		}else if(StrKit.isBlank(trueName)){
			renderResult(6);
			return;
		}else if(trueName.length()>20){
			renderResult(7);
			return;
		}else if(StrKit.isBlank(phonenumber)){
			renderResult(8);
			return;
		}else if(!ValidateKit.Mobile(phonenumber)){
			renderResult(9);
			return;
		}else if(!StrKit.isBlank(remark)&&remark.length()>500){
			renderResult(10);
			return;
		}else{
			//保存
			if(adminService.addUser(new Admin()
				.set("username", username)
				.set("password", new DefaultPasswordService().encryptPassword(password))
				.set("trueName", trueName)
				.set("phonenumber", phonenumber)
				.set("enabled", enabled)
				.set("remark", remark))){
				renderSuccess();
				return;
			}
		}
		renderFailed();
	}

	@RequiresPermissions("auth:admin:edit")
	public void toEdit(){
		int id = getParaToInt(0,0);
		if(id!=0){
			setAttr("object", adminService.findById(id));
		}
		render("edit.jsp");
	}
	
	/**
	 * 更新
	 * @return -1：异常，0：成功，1：姓名为空，2：姓名过长，3：手机号码为空，4：手机号码不正确，5：备注过长
	 */
	@RequiresPermissions("auth:admin:edit")
	public void doEdit(){
		//用户ID
		String userid = getPara("userid");
		//真实姓名
		String trueName = getPara("trueName");
		//手机号码
		String phonenumber = getPara("phonenumber");
		//备注
		String remark = getPara("remark");
		//是否可用
		int enabled = getParaToInt("enabled",0);
		if(StrKit.isBlank(userid)){
			renderFailed();
			return;
		}else if(StrKit.isBlank(trueName)){
			renderResult(1);
			return;
		}else if(trueName.length()>20){
			renderResult(2);
			return;
		}else if(StrKit.isBlank(phonenumber)){
			renderResult(3);
			return;
		}else if(!ValidateKit.Mobile(phonenumber)){
			renderResult(4);
			return;
		}else if(!StrKit.isBlank(remark)&&remark.length()>500){
			renderResult(5);
			return;
		}else{
			//更新
			if(adminService.editUser(new Admin()
				.set("id", userid)
				.set("trueName", trueName)
				.set("phonenumber", phonenumber)
				.set("enabled", enabled)
				.set("remark", remark))){
				renderSuccess(adminService.findById(Integer.valueOf(userid)));
				return;
			}
		}
		renderFailed();
	}
	
	@RequiresPermissions("auth:admin:edit")
	public void toEditPwd(){
		int id = getParaToInt(0,0);
		if(id!=0){
			setAttr("object", adminService.findById(id));
		}
		render("editPwd.jsp");
	}
	
	/**
	 * 更新密码
	 * @return -1：异常，0：成功，1：密码为空，2：密码过长
	 */
	@RequiresPermissions("auth:admin:edit")
	public void doEditPwd(){
		//用户ID
		String userid = getPara("userid");
		//密码
		String password = getPara("password");
		if(StrKit.isBlank(userid)){
			renderFailed();
			return;
		}else if(StrKit.isBlank(password)){
			renderResult(1);
			return;
		}else if(password.length()>100){
			renderResult(2);
			return;
		}else{
			//更新
			if(adminService.editUser(new Admin()
				.set("id", userid)
				.set("password", new DefaultPasswordService().encryptPassword(password)))){
				renderSuccess();
				return;
			}
		}
		renderFailed();
	}
	
	/**
	 * 删除
	 * @return -1：删除失败，0：删除成功
	 */
	@RequiresPermissions("auth:admin:delete")
	public void doDelete(){
		int id = getParaToInt(0,0);
		if(id!=0&&adminService.delUser(id)){
//			logger.info("删除用户【"+id+"】，并删除相应用户的角色关联信息");
			renderSuccess();
			return;
		}
		renderFailed();
	}

	@RequiresPermissions("auth:admin:accredit")
	public void toAccredit(){
		int userid = getParaToInt(0,0);
		if(userid!=0){
			setAttr("userid", getPara(0));
			List<Record> roles = roleService.findAllRoles();
			List<Record> selectedRoles = roleService.findRolesByUser(userid);
			for(Record role : roles){
				for(Record selected : selectedRoles){
					if(role.getInt("id")==selected.getInt("id")){
						role.set("checked", true);
						break;
					}
				}
			}
			setAttr("roles", roles);
		}
		render("accredit.jsp");
	}
	
	/**
	 * 用户角色设置
	 * @return -1：失败，0：成功，1：没有选择角色
	 */
	@RequiresPermissions("auth:admin:accredit")
	public void doAccredit(){
		int userid = getParaToInt("userid",0);
		String[] roles = getParaValues("roleid");
		if(userid==0){
			renderFailed();
			return;
		}else if(roleService.saveUserRole(userid, roles)){
			renderSuccess();
			return;
		}
		renderFailed();
	}
}
